/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: BookListView.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.view.bean.Book;

/**
 * ================================================
 * 描   述：交易盘口
 * ================================================
 */

public class BookListView extends LinearLayout implements BookView.OnClickListener {
    LayoutInflater layoutInflater;
    private View latestPriceLayout;
    private TextView priceTx,priceTx2;
    private int bidBookSize=16;
    private int askBookSize=16;
    private List<BookView> bookViewList = new ArrayList<>();
    private final DisplayMetrics mDisplayMetrices = getResources().getDisplayMetrics();
    private int mDefaultWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 250, mDisplayMetrices);

    private int mDefaultHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 21, mDisplayMetrices);
    private OnBookListViewClikcLintener mListener;


    public BookListView(Context context) {
        this(context,null);
    }

    public BookListView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public BookListView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    /**
     * 初始化
     * @param context
     * @param attrs
     */
    private void init(Context context, AttributeSet attrs) {
        int totalHeight = getHeight();
        layoutInflater = LayoutInflater.from(context);
//        latestPriceLayout = layoutInflater.inflate(R.layout.merge_trade_latest_price_layout, this, true);
        latestPriceLayout = layoutInflater.inflate(R.layout.merge_trade_latest_price_layout, null);
        priceTx = latestPriceLayout.findViewById(R.id.averagePrice);
        priceTx.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    Book book = new Book();
                    book.setPrice(priceTx.getText().toString());
                    mListener.onClick(book);
                }
            }
        });
        priceTx2 = latestPriceLayout.findViewById(R.id.price2);
        for (int i = 0; i < bidBookSize; i++) {
            BookView bookView1 = new BookView(context);
            bookView1.setPaddingTop(2);
            bookView1.setPaddingBottom(2);
            bookView1.setViewWH(300,75);
            bookView1.setOnClickLintener(this);
            addView(bookView1);
            bookViewList.add(bookView1);
        }

        addView(latestPriceLayout);

        for (int i = 0; i < askBookSize; i++) {
            BookView bookView1 = new BookView(context);
            bookView1.setPaddingTop(2);
            bookView1.setPaddingBottom(2);
            bookView1.setViewWH(300,75);
            bookView1.setOnClickLintener(this);
            addView(bookView1);
            bookViewList.add(bookView1);
        }

    }

    public void setBidAskSize(int bidSize,int askSize){
        changeLayout(bidSize,askSize);
        bidBookSize = bidSize;
        askBookSize = askSize;
    }

    public int getBidSize(){
        return bidBookSize;
    }

    public int getAskSize(){
        return askBookSize;
    }

    /**
     * 改变布局
     * @param bidSize
     * @param askSize
     */
    private void changeLayout(int bidSize, int askSize) {
        //只显示上面的卖单
        if (bidSize==0){
            removeView(latestPriceLayout);
            addView(latestPriceLayout,askSize);
            return;
        }else if (askSize==0){
            //只显示下面的买单
            removeView(latestPriceLayout);
            addView(latestPriceLayout,0);
            return;
        }else{
            removeView(latestPriceLayout);
            addView(latestPriceLayout,askSize);
        }

    }

    /**
     * 更新最新价
     * @param price1
     * @param price2
     * @param priceColor
     */
    public void updateLatestPrice(String price1,String price2,int priceColor){
        priceTx.setText(price1);
        priceTx.setTextColor(priceColor);
        priceTx2.setText(price2);
    }

    /**
     * 更新Book列表
     */
    public void updateBidBookList(List<Book> list){
//        resetBookList();
        if (list != null) {
            if (list.size()>bidBookSize) {
                list = list.subList(0,bidBookSize);
            }
            //买盘再下面
            int startI = bookViewList.size()-bidBookSize;
            for (int i = startI; i < bookViewList.size(); i++) {
                if (startI+list.size()>i) {
                    Book book = list.get(i-startI);
                    bookViewList.get(i).setBook(book);
                }
            }
        }
    }

    /**
     * 更新Book列表
     */
    public void updateAskBookList(List<Book> list){
//        resetBookList();
        if (list != null) {
            if (list.size()>askBookSize) {
                list = list.subList(0,askBookSize);
            }
            Collections.reverse(list);
            //卖盘在上面
            for (int i = 0; i < bookViewList.size(); i++) {
                if (list.size()>i) {
                    Book book = list.get(i);
                    bookViewList.get(i).setBook(book);
                }
            }
        }
    }

    /**
     * 重置清空View
     */
    public void resetBookList(boolean isResetLastPrice){
        if (bookViewList != null) {
            for (BookView bookView : bookViewList) {
                Book book = bookView.getBook();
                if (book != null) {
                    book.setPrice("--");
                    book.setVolume("--");
                    book.setProgress(0);
                    bookView.setBook(book);
                }

            }
            if (isResetLastPrice) {
                priceTx.setText("");
                priceTx2.setText("");
            }
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width;
        int height;

        // Get measureSpec mode and size values.
        final int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
        final int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        final int measureHeight = MeasureSpec.getSize(heightMeasureSpec);

        // The RangeBar width should be as large as possible.
        if (measureWidthMode == MeasureSpec.AT_MOST) {
            width = measureWidth;
        } else if (measureWidthMode == MeasureSpec.EXACTLY) {
            width = measureWidth;
        } else {
            width = mDefaultWidth;
        }

        // The RangeBar height should be as small as possible.
        if (measureHeightMode == MeasureSpec.AT_MOST) {
            height = Math.min(mDefaultHeight, measureHeight);
        } else if (measureHeightMode == MeasureSpec.EXACTLY) {
            height = measureHeight;
        } else {
            height = mDefaultHeight;
        }
        updateBookViewWH(width,height);
        setMeasuredDimension(width, height);
    }

    private void updateBookViewWH(int width, int height) {
        int h = (height - latestPriceLayout.getMeasuredHeight())/(bidBookSize+askBookSize);
        for (BookView bookView : bookViewList) {
            bookView.setViewWH(width,h);
        }
    }

    public void setOnItemLintener(OnBookListViewClikcLintener lintener){
        mListener = lintener;
    }

    @Override
    public void onClick(Book book) {
        if (mListener != null) {
            mListener.onClick(book);
        }
    }

    public interface OnBookListViewClikcLintener{
        void onClick(Book book);
    }
}
